import java.io.*;
import java.net.*;

public class Client {

    private static final String SERVER_ADDRESS = "localhost"; // 服务器地址
    private static final int SERVER_PORT = 12345;            // 服务器端口

    public static void main(String[] args) {
        try (Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
             BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

            // 启动接收消息的线程
            new Thread(new IncomingMessageHandler(in)).start();

            // 用户输入消息并发送给服务器
            String message;
            while (true) {
                System.out.print("请输入消息：");
                message = userInput.readLine();
                if (message != null) {
                    out.println(message); // 发送消息给服务器
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 处理从服务器接收到的消息
    private static class IncomingMessageHandler implements Runnable {
        private BufferedReader in;

        public IncomingMessageHandler(BufferedReader in) {
            this.in = in;
        }

        @Override
        public void run() {
            String message;
            try {
                while ((message = in.readLine()) != null) {
                    System.out.println("收到消息: " + message); // 打印服务器广播的消息
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}